/**
 * 
 */
package design_pattern.proxy.example2;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.Vector;

/**
 * @author linzq
 * 
 */
public class VectorProxy implements InvocationHandler {

  private Object proxyObject;

  /**
   * 
   */
  public VectorProxy(Object obj) {
    this.proxyObject = obj;
  }

  public static Object factory(Object obj) {
    Object o = Proxy.newProxyInstance(obj.getClass().getClassLoader(),
            obj.getClass().getInterfaces(), new VectorProxy(obj));
    return o;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    System.out.println("Before calling " + method + ".");
    if (args != null) {
      for (int i = 0; i < args.length; i++) {
        System.out.println("argument " + i + ":" + args[i]);
      }
    }
    // Object tarObj = ((VectorProxy)Proxy.getInvocationHandler(proxy));
    Object result = method.invoke(proxy, args);
    System.out.println("After calling " + method + ".");
    return result;
  }

  public static void main(String[] args) {
    List v = null;
    v = (List) factory(new Vector(10));
    v.add("new");
    v.add("york");
  }
}
